package sample.analysis.controller;

import javafx.concurrent.Service;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import sample.analysis.util.FileCopyUtil;
import sample.analysis.util.NmonUtil;
import sample.util.H2dbCRUDUtil;

import java.io.File;
import java.sql.ResultSet;
import java.util.Date;
import java.util.List;

public class MyController {

    private String Filename;

    private String putfilepath="";
    private String pathname = "";

    public static String ANALYSIS_UI_reoportFilePath;

    outputReportService oprs = new outputReportService();

    @FXML
    private VBox ANALYSIS_UI_MAIN;

    @FXML
    private MenuItem selectNmonFile;

    @FXML
    private MenuItem selectJsonFile;


    @FXML
    private MenuItem outPutReport;

    @FXML
    private WebView Analysis_webView;


    @FXML
    void outPutReportOnAction(ActionEvent event) {

        System.out.println("选择报告导出文件夹");
        DirectoryChooser dc = new DirectoryChooser();
        dc.setTitle("选择一个文件夹");
//        dc.setInitialDirectory(new File("D:" + File.separator));
        File file = dc.showDialog(ANALYSIS_UI_MAIN.getScene().getWindow());
        System.out.println("导出报告："+file.getAbsolutePath());

        FileCopyUtil fileCopyUtil = new FileCopyUtil();
        pathname = ANALYSIS_UI_reoportFilePath.replace("*.nmon","").replace("*","");
        putfilepath = file.getAbsolutePath()+File.separator+pathname;
        fileCopyUtil.copyDir(new File("").getAbsolutePath()+File.separator+"dist",putfilepath);






        if (oprs.getState().toString().contains("READY")) {
            oprs.start();
        } else {
            oprs.restart();
        }

        }

    @FXML
    void selectNmonFileOnAction(ActionEvent event) {
//        System.out.println("选择nmon文件");
        FileChooser fileChooser = new FileChooser();
        // 初始打开的位置
//        fileChooser.setInitialDirectory(new File("."));

        fileChooser.setTitle("选择nmon文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Text Files", "*.nmon"),
                new FileChooser.ExtensionFilter("All Files", "*.*"));
//        File selectedFile = fileChooser.showOpenDialog(UI_MAIN.getScene().getWindow());
        List<File> fileList = fileChooser.showOpenMultipleDialog(ANALYSIS_UI_MAIN.getScene().getWindow());
//        if (fileList != null) {
//            String filepath = fileList.get(0).getAbsolutePath();
//            System.out.println("选取文件路径为" + filepath);
//        }
        //处理文件，生成结果json文件
//        System.out.println(fileList.get(0).getAbsolutePath());
//        System.out.println(fileList.get(0).getParent());
//        System.out.println(new File(fileList.get(0).getParent()).getName());
//        System.out.println(fileList.get(0).getName());
//        try {
//            System.out.println(fileList.get(0).getCanonicalPath());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println(fileList.get(0).getPath());
//        System.out.println(fileList.get(0).getFreeSpace());
//        try {
//            System.out.println(fileList.get(0).getCanonicalFile());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        String jsonFilename = new File(fileList.get(0).getParent()).getName();
        Filename = jsonFilename;
        NmonUtil nmonUtil = new NmonUtil();
        try {
            nmonUtil.writeAnalysisResultToJson(fileList,fileList.get(0).getParent(),jsonFilename+".json");
        }catch (Exception e){
            System.out.println("生成解析结果文件异常");
        }



        //         get the web engine
        WebEngine e = Analysis_webView.getEngine();
        // 设置支持js，默认为false
        e.setJavaScriptEnabled(true);
        // 设置缓存模式：不使用缓存
        System.setProperty("sun.net.http.allowRestrictedHeaders","true");
        // load a website
        //加载本地网页 绝对路径
//        e.load("file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?data/nmonResult/nmonResult");
        //加载本地网页 相对路径
        File htmlfile = new File("dist"+File.separator+"index.html");
//        System.out.println(htmlfile.getAbsolutePath());
        e.load("file://"+htmlfile.getAbsolutePath());

//        e.load("file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?"+"data/2222/"+jsonFilename);
//        e.load("http://localhost:8080/?2222");
//        System.out.println("当前展示的问题为："+"file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?"+"data/"+jsonFilename+"/"+jsonFilename);


//
    }

    @FXML
    void selectJsonFileOnAction(ActionEvent event) {
//        System.out.println("选择json文件");
        FileChooser fileChooser = new FileChooser();
        // 初始打开的位置
//        fileChooser.setInitialDirectory(new File("."));

        fileChooser.setTitle("选择json文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Text Files", "*.json"),
                new FileChooser.ExtensionFilter("All Files", "*.*"));

        File selectedFile = fileChooser.showOpenDialog(ANALYSIS_UI_MAIN.getScene().getWindow());

        if (selectedFile != null) {

            String filepath = selectedFile.getAbsolutePath();
            Filename = new File(selectedFile.getParent()).getName();
            NmonUtil nmonUtil = new NmonUtil();
            try {
            nmonUtil.writeAnalysisResultToJS(filepath);
            }catch (Exception e){
                System.out.println("解析结果文件异常");
            }
        }



        //         get the web engine

        WebEngine e = Analysis_webView.getEngine();
        // 设置支持js，默认为false
        e.setJavaScriptEnabled(true);

        // 设置缓存模式：不使用缓存
        System.setProperty("sun.net.http.allowRestrictedHeaders","true");
        // load a website
        //加载本地网页 绝对路径
//        e.load("file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?data/nmonResult/nmonResult");
        //加载本地网页 相对路径
        File htmlfile = new File("dist"+File.separator+"index.html");
//        System.out.println(htmlfile.getAbsolutePath());   +"?data/nmonResult/nmonResult"
        e.load("file://"+htmlfile.getAbsolutePath());

//        e.load("file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?"+"data/2222/"+jsonFilename);
//        e.load("http://localhost:8080/?2222");
//        System.out.println("当前展示的问题为："+"file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?"+"data/"+jsonFilename+"/"+jsonFilename);


//
    }

    @FXML
    private void initialize() {


        //         get the web engine
        WebEngine e = Analysis_webView.getEngine();
        // 设置支持js，默认为false
        e.setJavaScriptEnabled(true);
        // 设置缓存模式：不使用缓存
        System.setProperty("sun.net.http.allowRestrictedHeaders","true");
        // load a website
        //加载本地网页 绝对路径
//        e.load("file://"+"/Users/wutongchun/IdeaProjects/javaFX/javaFX_NmonAnalysisTools/dist/index.html?data/nmonResult/nmonResult");
        //加载本地网页 相对路径
        File htmlfile = new File("dist"+File.separator+"index.html");
//        System.out.println(htmlfile.getAbsolutePath());
        e.load("file://"+htmlfile.getAbsolutePath());


    }

    //解析nmon结果
    private class outputReportService extends Service<Number> {
        double progress = 0.0;
        double count = 0.0;
        @Override
        protected javafx.concurrent.Task<Number> createTask() {
            javafx.concurrent.Task<Number> task = new javafx.concurrent.Task<Number>() {


                @Override
                protected void updateValue(Number value) {
                    super.updateValue(value);
                    if (value.intValue() < 0) {
                        progress = 0.0;
                        count = 0.0;
                        outputReportService.this.cancel();
                    } else {
                        if (value.intValue() >= 1) {
                            progress = 0.0;
                            count = 0.0;
                            outputReportService.this.cancel();

                            //更新解析信息入库和表格展示

                        }
                    }

                }
                @Override
                protected Number call() {
                    //导出完，记录报告路径
                    //更新解析信息入库和表格展示
                    //数据库连接
                    sample.controller.MyController.h2dbCRUDUtil.insertOrUpdateSql("UPDATE nmonMonitorList_table SET toLink = '"+putfilepath+"' WHERE nmonName like '%"+pathname+"%'");
                    ResultSet resultSet = sample.controller.MyController.h2dbCRUDUtil.selectSql("Select id from nmonMonitorList_table where nmonName like '%"+pathname+"%'");
                    try {
                        while (resultSet.next()){
//                                        System.out.println(resultSet.getInt("id"));
                            sample.controller.MyController.monitorHistoryDataList.get(resultSet.getInt("id")-1).setToLink(putfilepath);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        System.out.println(e.getMessage());
                    }

                    return 1;
                }

            };
            return task;
        }
    }




}
